/**
 * 登录功能的核心流程包括：

验证用户输入的用户名和密码。
生成 JWT（JSON Web Token）作为登录凭证。
将登录信息（如登录时间、设备、IP 等）存储到 user-login 表中。
 * 
 */
import { Injectable } from '@nestjs/common';

import { User } from 'src/entities/user/user.entity'; //用户数据
import { UserLogin } from 'src/entities/user/user-login.entity'; //用户数据
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { BusinessException } from 'src/common/exceptions/business.filter';
import { BUSINESS_ERROR_CODE } from '@/config/error.code';
import * as svgCaptcha from 'svg-captcha';
import * as bcryptjs from 'bcryptjs';
import { JwtService } from '@nestjs/jwt';
interface IRegister {
  name: string;
  password: string;
  phone: string;
}
@Injectable()
export class AuthService {
  constructor(
    private jwtService: JwtService,
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
    @InjectRepository(UserLogin)
    private readonly userLoginRepository: Repository<UserLogin>,
  ) {}
  // 登录接口
  async login(body: any) {
    // 姓名或手机号登录+密码验证
    try {
      const { name, password, ip, device, platform_type } = body;

      const findUser = await this.userRepository
        .createQueryBuilder('user')
        .addSelect('user.password') //添加密码字段
        .where([
          {
            name,
          },
          {
            phone: name,
          },
        ])
        .getOne();
      if (!findUser) {
        return {
          code: BUSINESS_ERROR_CODE.USER_PASSWORD_ERROR,
          result: '用户名不存在',
        };
      }

      // 找到了对比密码
      const compareRes: boolean = bcryptjs.compareSync(
        password,
        findUser.password,
      );
      if (!compareRes) {
        return {
          code: BUSINESS_ERROR_CODE.USER_PASSWORD_ERROR,
          result: '密码错误',
        };
      }

      const payload = {
        name: findUser.name,
        phone: findUser.phone,
        user_id: findUser.user_id,
        date: new Date().getTime(),
      };
      const token = this.jwtService.sign(payload);
      // 在用户登录表中存储登录信息 登录时间 登录设备 登录IP token 平台类型
      //如果user_id存在，则更新token，否则插入一条新的记录
      let userLogin = await this.userLoginRepository.findOne({
        where: {
          user_id: findUser.user_id,
          platform_type,
        },
      });
      if (userLogin) {
        await this.userLoginRepository.update(
          { user_id: findUser.user_id, platform_type },
          {
            login_time: new Date(),
            ip,
            device,
            token,
          },
        );
      } else {
        await this.userLoginRepository.save({
          user_id: findUser.user_id,
          login_time: new Date(),
          ip,
          device,
          platform_type,
          token,
        });
      }

      return {
        result: {
          message: '登录成功',
          access_token: token,
        },
      };
    } catch (error) {
      throw new BusinessException(error);
    }
  }
  // 注册
  async register(body: IRegister) {
    const { name, password, phone } = body;
    try {
      if (!name || !password || !phone) {
        return {
          code: BUSINESS_ERROR_CODE.COMMON,
          result: '参数错误',
        };
      }
      // 一个手机号一个平台自能注册一次
      // 查询是否已经注册
      const user = await this.userRepository.findOne({
        where: {
          phone,
        },
      });
      if (user) {
        return {
          code: BUSINESS_ERROR_CODE.COMMON,
          result: '该用户手机号已经注册',
        };
      } else {
        const havUser = await this.userRepository.findOne({
          where: {
            name,
          },
        });
        if (havUser) {
          return {
            code: BUSINESS_ERROR_CODE.COMMON,
            result: '该用户名称已经注册',
          };
        } else {
          // new User是为了 走到 @BeforeInsert()中来对password进行加密处理
          const data = new User();
          data.name = name;
          data.password = password;
          data.phone = phone;
          // 注册
          const user = await this.userRepository.save(data);
          return '';
        }
      }
    } catch (error) {
      throw new BusinessException('error');
    }
  }

  // 生成验证码
  generateCaptcha() {
    const captcha = svgCaptcha.create({
      size: 4, // 验证码长度
      ignoreChars: '0o1i', // 忽略容易混淆的字符
      noise: 2, // 干扰线条数
      color: true, // 验证码字符颜色
      background: '#f0f0f0', // 背景颜色
    });
    return captcha;
  }

  // 验证验证码
  validateCaptcha(input: string, captchaText: string): boolean {
    return input.toLowerCase() === captchaText.toLowerCase();
  }
}
